
/* globals svgEditor */
import { isValidUnit } from '../../common/units.js'
import imagePropertiesDialogHTML from './view.html'


const template = document.createElement('template')
template.innerHTML = imagePropertiesDialogHTML
/**
 * @class SeImgPropDialog
 */
export class SeViews extends HTMLElement {
  /**
    * @function constructor
    */
  constructor() {
    super()
    // create the shadowDom and insert the template
    this._shadowRoot = this.attachShadow({ mode: 'open' })

    this._shadowRoot.append(template.content.cloneNode(true))
    this.$dialog = this._shadowRoot.querySelector('#svg_createment')
    this.$cancelBtn = this._shadowRoot.querySelector('.tool_prefs_cancel')
    this.$delBtn = this._shadowRoot.querySelector('.tool_prefs_del')
    this.$changeContent = this._shadowRoot.querySelector('.changeContent')
    this.$content = this._shadowRoot.querySelector('.content')
    this.$detailContent =   this._shadowRoot.querySelector('.content div')
    this.$editorObj = null;


  }

  /**
   * @function init
   * @param {any} name
   * @returns {void}
   */
  init(i18next) {


  }

  /**
   * @function observedAttributes
   * @returns {any} observed
   */
  static get observedAttributes() {
    return ['dialog', 'common-ok', 'common-cancel','time-change']
  }

  /**
   * @function attributeChangedCallback
   * @param {string} name
   * @param {string} oldValue
   * @param {string} newValue
   * @returns {void}
   */
  async attributeChangedCallback(name, oldValue, newValue) {
    if (oldValue === newValue) return
    switch (name) {
      case 'dialog':
        if (newValue === 'open') {
          this.$dialog.open()
          await this.updateLib()
          await this.ViewContentUpdate();
          break
        } else {
          this.$dialog.close()
          break
        }
        break
      case 'common-cancel':
        this.$cancelBtn.textContent = newValue
        break
      case 'time-change':
        this.$editorObj= newValue
        await this.ViewContentUpdate();
        break
      default:
        super.attributeChangedCallback(name, oldValue, newValue)
        break
    }
  }


  async ViewContentUpdate() {
    const [x, y] = svgEditor.configObj.curConfig.dimensions

    $(this._shadowRoot).find('.content').find('div>div>img').off('click').on('click',async function(e) {
      e.stopPropagation()
      e.preventDefault()
      $(this).addClass('press').siblings().removeClass('press')
      var imgSrc= $(this).attr('data-set');

      let primitiveType = $(this).data('key');
      let primitiveDesc = $(this).data('title');
      var reallyimgSrc = decodeURIComponent(escape(atob(imgSrc)))
      svgEditor.svgCanvas.clear()
      const $imgDialog = svgEditor.svgCanvas.$id('se-view')
      $imgDialog.setAttribute('dialog', 'close')
      svgEditor.storage.setItem('svg-edit-primitiveDesc', primitiveDesc)
      svgEditor.storage.setItem('svg-edit-primitiveType', primitiveType)

      await svgEditor.loadSvgString(reallyimgSrc)
      svgEditor.svgCanvas.setResolution(x, y)
      svgEditor.updateCanvas()
      svgEditor.layersPanel.populateLayers()
  })

  }
  /**
   * @function get
   * @returns {any}
   */


  /**
   * @function get
   * @returns {any}
   */


   async updateLib () {
    try {
      const response1 = await fetch(`${svgEditor.configObj.curConfig.serviceUrl}/sys/dict/item/261`)
      const  data1 = (await response1.json()).data;
      const response = await fetch(`${svgEditor.configObj.curConfig.serviceUrl}/svg/primitive/list`)
      const  data = (await response.json()).data;
      var mapobj={}
      for(let i in data1){
        mapobj[data1[i]['dict_value']   ] =  data1[i]['dict_label']
      }
      var obj={}
      for(let i =0;i<data1.length;i++){
        var key = data1[i]['dict_value'] ;
        obj[key] =[]
      }
      var merageData ={...obj,...data};
      
     
      let changeTemplate = '';
      $(this._shadowRoot).find('.content').empty();
      Object.entries(merageData).forEach(([key, value],i) => {
        let changeContent = '';
        if(i>=1){
          var  divItem = $('<div></div>')
          changeTemplate +=  `<div>${mapobj[key]}</div>`
        }else{
          var  divItem =$(`<div class='active'></div>`)
          changeTemplate +=  `<div class='active'>${mapobj[key]}</div>`
        }

       if(!value.length){
        changeContent+= `<div></div> `
        divItem.append($(changeContent))
        window.$(this._shadowRoot).find('.content').append(divItem)

       }else{
        value.forEach((gs) => {
          divItem.empty();
          let title = gs.title;
          let content = gs.content;
          if (!title) {
            return; //跳出循环
          }

          changeContent+= `<div><img title="${title}" data-key="${key}" data-title="${title}" data-set="${content}" src='data:image/svg+xml;base64,${content}'><span><input class='ckinput' type=checkbox name="delKeys" data-key="${key}" data-title="${title}" />${title}</span> </div> `
          divItem.append($(changeContent))
          window.$(this._shadowRoot).find('.content').append(divItem)

        })

       }
       
       
      })
      // window.$(this._shadowRoot).find('.changeContent').append($(changeTemplate))
      this.$changeContent.innerHTML = changeTemplate;
    } catch (error) {
      console.error(`could not read file:`, error)
    }
  }
 

  get dialog() {
    return this.getAttribute('dialog')
  }

  /**
   * @function set
   * @returns {void}
   */
  set dialog(value) {
    this.setAttribute('dialog', value)
  }

  /**
   * @function connectedCallback
   * @returns {void}
   */
  connectedCallback() {
    const onCancelHandler = () => {
      const closeEvent = new CustomEvent('change', {
        detail: {
          dialog: 'closed'
        }
      })
      this.dispatchEvent(closeEvent)
    }

    const onDelHandler= async () => {
      const params = [];
      var cks = $(this._shadowRoot).find('.ckinput:checked')
      Array.from(cks).forEach(elem => {
        const key = $(elem).data('key');
        const title = $(elem).data('title');
        params.push({type:key, name: title})
      })

      const ok = await seConfirm(svgEditor.i18next.t('notification.removePrimitive'))
      const success = svgEditor.i18next.t('notification.removeSuccess')
      const fail = svgEditor.i18next.t('notification.removeFailed')
      if (ok == 'Ok') {
        const response = await fetch(`${svgEditor.configObj.curConfig.serviceUrl}/svg/primitive`, {
          method: 'DELETE',
          headers: {
            'Content-type': 'application/json'
          },
          body: JSON.stringify(params)
        });
        const json = await response.json()
        const message = svgEditor.i18next.t(json.code === '100000' ? success : fail)
        await seAlert(message)
        await this.updateLib()
      }

    }

    svgEditor.$click(this.$cancelBtn, onCancelHandler)

    svgEditor.$click(this.$delBtn, onDelHandler)


    const {svgCanvas} = svgEditor
    // this.$changeContent = this._shadowRoot.querySelector('.changeContent')


    var a = $(this._shadowRoot);
    $(this._shadowRoot).find('.changeContent').on('click','div',function(){
        $(this).addClass('active').siblings().removeClass("active")
        a.find('.content>div').eq($(this).index()).addClass('active').siblings().removeClass('active')

    })
  }
}

// Register
customElements.define('se-view-dialog', SeViews)
